package Jdbc;

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Connection;

import Model.Editor;
import Model.Hakem;
import Model.Profil;
import Model.Rol;
import Model.Yazar;
import Model.Uye;


public class Jdbc {
	
	
	static Connection con = null;
	static Statement st = null;
	static ResultSet rs = null;

    static public void Connect(){
    		
		    String url = "jdbc:postgresql://localhost:5432/yazgellab";
		    String user = "postgres";
		    String password = "12345";
		
		    try {
		    	Class.forName("org.postgresql.Driver");
		        con = DriverManager.getConnection(url, user, password);
		
		    } catch (Exception ex) {
		      System.out.println("baglanilamadi");
		
		    }
      }
    
 
	static public Uye uyeSorgula(String username, String pass){
		Connect();
		Uye uye = null;
		try {
			st = con.createStatement();
			rs = st.executeQuery("SELECT * FROM uye WHERE email='" + username + "' AND sifre='" + pass + "'");
			if (rs.next()){
				
				uye = new Uye(rs.getString(2), rs.getString(3), null, null, rs.getString(1));
				rs = st.executeQuery("SELECT * FROM profil WHERE uye_pk = '" + rs.getString(1) +"'");
				if (rs.next()) {
					Profil profil = new Profil(rs.getString(8), rs.getString(9), rs.getString(2), rs.getString(4), rs.getString(5), rs.getString(6), rs.getString(7), rs.getString(3));
					uye.setProfil(profil);
					Rol[] rol = new Rol[3];
					
					rs = st.executeQuery("SELECT * FROM yazar WHERE uye_pk = '" + uye.getUye_id() +"'");
					if (rs.next()){
						rol[0] = new Yazar(null);
					}
					else{
						rol[0]=null;
					}
					
					rs = st.executeQuery("SELECT * FROM hakem WHERE uye_pk = '" + uye.getUye_id() +"'");
					if (rs.next()){
						rol[1] = new Hakem(null);
					}
					else{
						rol[1]=null;
					}
					
					rs = st.executeQuery("SELECT * FROM editor WHERE uye_pk = '" + uye.getUye_id() +"'");
					if (rs.next()){
						rol[2] = new Editor(null);
					}
					else{
						rol[2]=null;
					}
					uye.setAktifRol(rol);
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return uye;
	}
	
	
    
    public void close(){
    	
	        try {
	            if (rs != null) {
	                rs.close();
	            }
	            if (st != null) {
	                st.close();
	            }
	            if (con != null) {
	                con.close();
	            }
	
	        } catch (SQLException ex) {
	            System.out.println("Kapatilamadi");
	        }
    }
}
